package com.ruoyi.common.utils.qiniu;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/7/3 9:57
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@Component("qiniuUploadUtil")
public class QiNiuUploadUtil {

	private static String baseUrl;
	private static String accessKey;
	private static String secretKey;
	private static String bucketname;

	//秘钥配置
	private static Auth auth;

	@Value("${haoqi.qiniu.baseUrl}")
	public void setBaseUrl(String baseUrl) {
		QiNiuUploadUtil.baseUrl = baseUrl;
	}

	@Value("${haoqi.qiniu.accessKey}")
	public void setAccessKey(String accessKey) {
		QiNiuUploadUtil.accessKey = accessKey;
	}

	@Value("${haoqi.qiniu.secretKey}")
	public void setSecretKey(String secretKey) {
		QiNiuUploadUtil.secretKey = secretKey;
	}

	@Value("${haoqi.qiniu.bucketname}")
	public void setBucketname(String bucketname) {
		QiNiuUploadUtil.bucketname = bucketname;
	}



	// 指定上传的Zone的信息
	// 第一种 指定具体要上传的zone
	// 		当上传的地区是华东时
//	Zone z = Zone.zone0();
	//		当上传的地区是华北时
//	Zone z = Zone.zone1();
	//		当上传的地区是华南时
//	Zone z = Zone.zone2();

	//第二种方式 自动获取 (代码找不到了....)


	Configuration c = new Configuration();
	//创建上传对象
	UploadManager uploadManager = new UploadManager(c);

	//简单上传 使用默认策略 只需要设置空间名就可以
	public static String getUpToken(String path){
		if(auth==null){
			auth=Auth.create(getAccessKey(),getSecretKey());
		}
		return auth.uploadToken(getBucketname(),null);
	}


	public void upload(byte[] data,String fileName){
		//调用put方法上传
		try {
			Response res = uploadManager.put(data, fileName, getUpToken(fileName));
			System.out.println(res.bodyString());
		} catch (QiniuException e) {
			e.printStackTrace();
		}
	}


	public static String getBaseUrl() {
		return baseUrl;
	}

	public static String getAccessKey() {
		return accessKey;
	}

	public static String getSecretKey() {
		return secretKey;
	}

	public static String getBucketname() {
		return bucketname;
	}




}
